package l2hc.gameserver.database;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DatabaseInstaller {
	
	private static final Logger _log = LoggerFactory.getLogger(DatabaseInstaller.class);
	
	private static final String SQL_DIR = "./sql";
	
	public static void checkDatabase() {
		File dir = new File(SQL_DIR);
		File[] sqlFiles = dir.listFiles(new SQLFilter());
		
		for(File f : sqlFiles)
			if(isTableExists(f))
				installTable(f);
	}
	
	private static boolean isTableExists(File tableName) {
		Connection con = null;
		PreparedStatement statement = null;
		ResultSet rset = null;
		
		try {
			con = DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement("SHOW TABLES LIKE '" + tableName.getName() + "'");
			rset = statement.executeQuery();
		} catch(SQLException e) {
			_log.info("", e);
		}
		
		return rset == null ? false : true;
	}
	
	private static void installTable(File table) {
		Connection con = null;
		PreparedStatement statement = null;
		StringBuilder sb = new StringBuilder();
		Scanner read;
		try {
			read = new Scanner(table);
			while(read.hasNext())
				sb.append(read.nextLine() + "\r\n");
			read.close();
			con = DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement(sb.toString());
			statement.execute();
		} catch(Exception e) {
			_log.info("", e);
		}
		
		_log.info("Installed table " + table.getName());
	}
	
	private static class SQLFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String name) {
			if(name.endsWith(".sql"))
				return true;
			return false;
		}
		
	}
}
